import React, { Component } from 'react'
import request from '../../utils/request'

export default class Header extends Component {
  state = {
    name: ''
  }
  handleChange = (e) => {
    this.setState({
      name: e.target.value
    })
  }
  handleUp = async (e) => {
    if (this.state.name.trim().length === 0) {
      return alert('不能为空')
    }
    if (e.keyCode === 13) {
      await request.post('/', {
        name: this.state.name,
        done: false
      })
      // 调用父级里面获取数据的方式，并渲染
      this.props.getList()
      this.setState({
        name: ''
      })
    }
  }
  render () {
    return (
      <header className='header'>
        <h1>todos</h1>
        <input className='new-todo' placeholder='What needs to be done?'
          autoFocus
          value={this.state.name}
          onChange={this.handleChange}
          onKeyUp={this.handleUp}
        />
      </header>
    )
  }
}